/**
 * ZHU framework. Copyright 2012-, all rights reserved.
 *
 * $Id: WebContextBase.java 12 2012-07-27 08:48:07Z zhuxiaopeng $
 * $Revision: 12 $
 * $Date: 2012-07-27 16:48:07 +0800 (五, 2012-07-27) $
 * $Author: zhuxiaopeng $
 */
package zhu.framework.web;

import java.util.logging.*;

import zhu.framework.util.*;

/**
 * <p>
 * </p>
 * 
 * @author $Author: zhuxiaopeng $
 * @version $Revision: 12 $ - $Date: 2012-07-27 16:48:07 +0800 (五, 2012-07-27) $
 */
public abstract class WebContextBase extends WebContext {

	/**
	 * このClassのデフォルトの<code>Logger</code>取得する。
	 * 特に理由のない限り、このClass内ではこのメソッドを通じてLoggerを取得することを推奨する。
	 * 
	 * @return このClassのデフォルトの<code>Logger</code>
	 */
	static private Logger getLogger() {
		final LoggerManager manager = LoggerManager.getInstance();
		final Logger logger = manager.getLogger(WebContextBase.class);
		return logger;
	}

	public WebContextBase() {
		super();
	}

	@Override
	public final WebSessionContext getSessionContext() {
		return getRequestContext().getSessionContext();
	}

	@Override
	public final WebRequestContext getRequestContext() {
		final WebRequestContext currentContext = getRequestContextStore().get();
		if (currentContext == null) {
			final IllegalStateException e = new IllegalStateException("WebRequestContext has not been initialized");
			final Logger logger = getLogger();
			logger.throwing("zhu.framework.web.WebContextBase", "getRequestContext", e);
			throw e;
		}
		return currentContext;
	}

	public final void constructRequestContext(final WebRequestContext context) {
		MyUtility.checkMethodParameterNotNull("context", context);
		//
		final Logger logger = getLogger();
		if (logger.isLoggable(Level.FINE)) {
			logger.fine(String.format("Constructing a WebRequestContext : %s", context));
		}
		//
		if (getRequestContextStore().get() != null) {
			if (logger.isLoggable(Level.WARNING)) {
				logger.warning(String.format("Attempting to over-write an existent WebRequestContext : previous=%s : new=%s",
						getRequestContextStore().get(), context));
			}
		}
		getRequestContextStore().set(context);
	}

	public final void destroyRequestContext() {
		final Logger logger = getLogger();
		if (logger.isLoggable(Level.FINE)) {
			logger.fine(String.format("Destructing a WebRequestContext : %s", getRequestContextStore().get()));
		}
		//
		if (getRequestContextStore().get() == null) {
			if (logger.isLoggable(Level.WARNING)) {
				logger.warning("Destroying non-existent WebRequestContext : something may be wrong in request handling system.");
			}
		}
		getRequestContextStore().remove();
	}

	/**
	 * <p>
	 * プロパティ<code>requestContextStore</code>の値を取得する。
	 * </p>
	 * 
	 * @return プロパティ<code>requestContextStore</code>の値
	 */
	private ThreadLocal<WebRequestContext> getRequestContextStore() {
		return requestContextStore;
	}

	private final ThreadLocal<WebRequestContext> requestContextStore = new ThreadLocal<WebRequestContext>();

}
